import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import 'flex.css/dist/data-flex.css';
import './uploader.css'
import imgUpload from 'assets/img/btn_uploade.png'

const noop = Function();
export default class Uploader extends Component {
    constructor(){
      super();
      this.renderFiles = this.renderFiles.bind(this);
    }
    static propTypes = {
        title: PropTypes.string,
        maxCount: PropTypes.number,
        onSelected: PropTypes.func,//选择图片之后
        onFileClick: PropTypes.func,//点击已经上传的图片时
        onSuccessed: PropTypes.func,//上传成功后
        onDelete: PropTypes.func,//点击删除时
        onUploadClick: PropTypes.func,
        onError: PropTypes.func,
        files: PropTypes.array,
        errorTip: PropTypes.object
    };

    static defaultProps = {
        title: '上传营业执照',
        maxCount: 4,
        files: [],
        onSelected: noop,
        onFileClick: noop,
        onDelete: noop,
        onError: noop,
        onSuccessed: noop,
        onUploadClick: noop,
        errorTip:{ maxError: maxCount => `最多只能上传${maxCount}张图片` }
    };

    _getFiles(){
      const onSelected = this.props.onSelected;
      const maxCount = this.props.maxCount;

      return new Promise((resolve, reject)=>{
        console.log('获取文件：')
        wx.chooseImage({
            count: maxCount, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                console.log('返回文件的id:')
                console.log(res.localIds)
                var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                onSelected && onSelected(localIds);
                resolve(localIds);
            }
        });
      })
    }

    handleUpdateFile(){
      if(this.props.onUploadClick()===false) return;
      if(!(wx && wx.chooseImage)){
        alert('请使用微信浏览器打开')
      }
      var uploadRes = [];

      this._getFiles()
        .then((files)=>{
          return files.map(file=>{
              return ()=>{
                return new Promise((resolve, reject)=>{
                  console.log('开始上传=====')
                  wx.uploadImage({
                      localId: file, // 需要上传的图片的本地ID，由chooseImage接口获得
                      isShowProgressTips: 1, // 默认为1，显示进度提示
                      success: function (res) {
                          console.log('上传成功====')
                          console.log(res);
                          resolve(res);
                      }
                  });
                })
              }
          })
        })
        .then(arrUploadTasks=>{
          function recordValue(results, value) {
              results.push(value);
              console.log('单次上传结果：')
              console.log(results);
              return results;
          }
          let pushValue = recordValue.bind(null, []);

          return arrUploadTasks.reduce((prev, next)=>{
            return prev.then(next).then(pushValue)
          }, Promise.resolve())
        })
        .then(arrRes=>{
          console.log('上传完成，执行 sucess')
          console.log(arrRes);
          this.props.onSuccessed(arrRes);
        })
    }

    renderFiles(files){
      const onFileClick = this.props.onFileClick;
      const onDelete = this.props.onDelete;
      return files.map((file,idx)=>{
        let fileStyle = {
            backgroundImage: `url(${file})`
        };
        return (
          <li className="ui-uploader-file bdr"
              key={idx}
              style={fileStyle}
              onClick={()=>{onFileClick(file, idx)} }
          >
          <i className="icon-upload-del icon30"
            onClick = {()=>{onDelete(file)}}
            ></i>
          </li>
        )
      })
    }

    render(){
      const { title, files } = this.props;
      return (
        <div className="p20">
          <div data-flex="main:left">
            <ul className="ui-uploader-files" data-flex="main:left">
              {this.renderFiles(files)}
            </ul>
            <div className="ui-uploader-ipt" onClick={this.handleUpdateFile.bind(this)}>
              <div className="tc">
                <img src={imgUpload} className="ui-uploader-btn"/>
              </div>
              <p className="ui-uploader-btntxt c-rd f20 tc">{ title }</p>
            </div>
          </div>
        </div>
      )
    }
};
